import axios from "axios";
import cookies from 'vue-cookies'
import Element from "element-ui"
import router from "@/router";
import store from "@/store";

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }
})

// 请求拦截器
// 从cookie中取出token携带在请求头中
request.interceptors.request.use(config => {
    config.headers['token'] = cookies.get('token')
    return config
})

// 响应拦截器
request.interceptors.response.use(
    response => {
        if (response.data.code === 401) {
            console.log(store.state.isRedirecting)
            if (!store.state.isRedirecting) { // 只有在没有跳转的情况下才进行跳转
                store.commit('setRedirecting', true); // 设置标志
                Element.Message.error(response.data.msg);
                router.push('/login');
            }
            return false;
        }
        if (response.data.code === 100) {
            return response.data
        } else {
            Element.Message.error(!response.data.msg ? '请求服务器异常,请联系管理员' : response.data.msg)
            // return Promise.reject(response.data.msg)
            return false
        }
    },
    error => {
        if (error.response.data) {
            error.massage = error.response.data.msg
        }
        Element.Message.error(error.massage, {duration: 3000})
        return Promise.reject(error)
    }
)
export default request